package com.stylefeng.guns.rest.modular.wz.api.v3.service.impl;

import com.baomidou.mybatisplus.annotations.Version;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.stylefeng.guns.rest.common.exception.BizExceptionEnum;
import com.stylefeng.guns.rest.common.persistence.dao.*;
import com.stylefeng.guns.rest.common.persistence.model.*;
import com.stylefeng.guns.rest.common.util.StringUtils;
import com.stylefeng.guns.rest.domain.ParamMap;
import com.stylefeng.guns.rest.domain.Res;
import com.stylefeng.guns.rest.enums.*;
import com.stylefeng.guns.rest.modular.wz.cache.CacheService;
import com.stylefeng.guns.rest.modular.wz.util.wz.DateUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.*;

/**
 * 实现类
 */
@Service
public class WzCommonServiceImplV3{

    @Autowired
    private CacheService cacheService;
    @Autowired
    private WzUserAdvRecordMapper userAdvRecordMapper;
    @Autowired
    private WzAdvMapper advMapper;
    @Autowired
    private WzAdvMapMapper advMapMapper;
    @Autowired
    private WzMapActivityMapper mapActivityMapper;
    @Autowired
    private WzMapRebateMapper mapRebateMapper;
    @Autowired
    private WzMapMergeMapper mapMergeMapper;


    public Res indexPics(ParamMap paramMap) {
        Long userCode = paramMap.getLongValid("userCode");
        String switchAdCode = paramMap.getStrValid("switchAdCode");
        if(StringUtils.isBlank(switchAdCode)){
            switchAdCode = paramMap.getStrMisValid("adCode");
        }
        //位置判断
        if(switchAdCode.length() != 6){
            return Res.fail(BizExceptionEnum.RES_Ad_Code_Abnormal);
        }
        //用户10天内广告红包领取记录
        List<Map<String,Object>>  userAdvRecords = new ArrayList<>();
        //头部图片-占位图片
        List<Map<String,Object>> topPics = new ArrayList<>();
        List<Map<String,Object>> topPic = cacheService.wzSysFile(EnWzSysFile.Type_Index_Top_Pics.getIndex());
        for(Map<String,Object> map:topPic){
            topPics.add(map);
        }
        //活动中心图片
        List<Map<String,Object>> activityPics = new ArrayList<>();
        //中部图片
        List<Map<String,Object>> middlePics = new ArrayList<>();
        //头部图片-红包图片
        List<Map<String,Object>> topRedpacketPic = cacheService.wzSysFile(EnWzSysFile.Type_Index_Top_Repacket_Pic.getIndex());
        //顶部刷新图片
        List<Map<String,Object>> topRefreshPic = cacheService.wzSysFile(EnWzSysFile.Type_Refresh_Pic.getIndex());
        paramMap.clear();
        paramMap.put("activityPics",activityPics);
        paramMap.put("middlePics",middlePics);
        paramMap.put("topRedpacketPic",topRedpacketPic.get(0));
        paramMap.put("topRefreshPic",topRefreshPic.get(0));
        //未登录
        if(userCode == null){
            paramMap.put("topPics",topPics);
            paramMap.put("userAdvRecords",userAdvRecords);
            return Res.success(paramMap);
        }else{//登录状态
            userAdvRecords = userAdvRecordMapper.selectMaps(new EntityWrapper<WzUserAdvRecord>().setSqlSelect("adv_id As jumpTarget").eq("user_code",userCode).eq("subtype",EnWzAdv.SUBTYPE_ADV.getIndex()).ge("create_time", DateUtil.yesterday(new Date(),15)));
            List<Map<String,Object>>  userRedpacketRecord = userAdvRecordMapper.selectMaps(new EntityWrapper<WzUserAdvRecord>().setSqlSelect("adv_map_id As jumpTarget").eq("user_code",userCode).eq("subtype",EnWzAdv.SUBTYPE_Redpacket_MapAdv.getIndex()).ge("create_time", DateUtil.yesterday(new Date(),10)));
            for(Map<String,Object> map:userRedpacketRecord){
                userAdvRecords.add(map);
            }
            paramMap.put("userAdvRecords",userAdvRecords);
            //广告
            String sql = "adv_id As jumpTarget,title,subtitle,cover_url As fileUrl,subtype As type,subtype As jumpType,subtype As height";
            List<Map<String,Object>> advs = advMapper.selectMaps(new EntityWrapper<WzAdv>().setSqlSelect(sql).eq("daily_total_number",0).like("screen_city",switchAdCode).eq("status",EnWzAdv.STATUS_RELEASE_no.getIndex()).eq("subtype",EnWzAdv.SUBTYPE_ADV.getIndex()).orderBy("release_time",false));
            for(Map<String,Object> map:advs){
                topPics.add(map);
            }
            //红包
            sql = "adv_map_id As jumpTarget,title,'' As subtitle,cover_url As fileUrl,subtype As type,subtype As jumpType,subtype As height";
            List<Map<String,Object>> redpackets = advMapper.selectMaps(new EntityWrapper<WzAdv>().setSqlSelect(sql).like("screen_city",switchAdCode).eq("status",EnWzAdv.STATUS_RELEASE_no.getIndex()).eq("subtype",EnWzAdv.SUBTYPE_Redpacket_MapAdv.getIndex()).orderBy("release_time",false));
            for(Map<String,Object> map:redpackets){
                topPics.add(map);
            }
            paramMap.put("topPics",topPics);
        }
        return Res.success(paramMap);
    }

    public Res indexAdvMapRecommend(ParamMap paramMap) {
        int pageNum = paramMap.getIntMisValid("pageNum");
        int pageSize = paramMap.getIntMisValid("pageSize");
        String switchAdCode = paramMap.getStrValid("switchAdCode");//行政编号
        if(StringUtils.isBlank(switchAdCode)){
            switchAdCode = paramMap.getStrMisValid("adCode");
        }
        //位置判断
        if(switchAdCode.length() != 6){
            return Res.fail(BizExceptionEnum.RES_Ad_Code_Abnormal);
        }
        int advMapCategoryFirst = paramMap.getIntMisValid("advMapCategoryFirst");//一级分类 0:全部
        //sql语句
        String sql = "adv_map_id AS advMapId,subtype,avatar_url AS avatarUrl,subtitle,name,longitude,latitude,share_link As shareLink,merchant_tel As merchantTel";
        EntityWrapper<WzAdvMap> entityWrapper=new EntityWrapper<>();
        entityWrapper.setSqlSelect(sql).like("ad_code", switchAdCode).eq("type", EnWzAdvMap.TYPE_Adv.getIndex()).in("status", new Integer[]{EnWzAdvMap.STATUS_Release.getIndex(), EnWzAdvMap.STATUS_RelesseEditors.getIndex(), EnWzAdvMap.STATUS_Edit_Reject.getIndex()});
        if(advMapCategoryFirst!=0){
            entityWrapper.eq("adv_map_category_first",advMapCategoryFirst).orderBy("sort", true).orderBy("daily_amount", false).orderBy("create_time", true);
        }else{
            entityWrapper.eq("is_recommend", EnWzMapActivity.IsRecommend_Yes.getIndex()).orderBy("RAND()");

        }
        List<Map<String, Object>> advMaplist = advMapMapper.selectMapsPage(new Page(pageNum,pageSize),entityWrapper);
        for(Map<String, Object> map:advMaplist){
            String mapActivitySql = "benefit";
            List<Map<String, Object>> mapActivitys = mapActivityMapper.selectMaps(new EntityWrapper<WzMapActivity>().setSqlSelect(mapActivitySql).eq("adv_map_id",Long.parseLong(map.get("advMapId").toString())).eq("status",EnWzMapActivity.STATUS_RELEASE.getIndex()).gt("surplus_number",0));
            map.put("mapActivitys",mapActivitys);
        }
        return Res.success(paramMap.data(advMaplist));
    }

    public Res newIndexPics(ParamMap paramMap) {
        Long userCode = paramMap.getLongValid("userCode");
        String switchAdCode = paramMap.getStrValid("switchAdCode");
        if(StringUtils.isBlank(switchAdCode)){
            switchAdCode = paramMap.getStrMisValid("adCode");
        }
        //位置判断
        if(switchAdCode.length() != 6){
            return Res.fail(BizExceptionEnum.RES_Ad_Code_Abnormal);
        }
        //用户10天内广告红包领取记录
        List<Map<String,Object>>  userAdvRecords = new ArrayList<>();
        //头部图片-占位图片
        List<Map<String,Object>> topPics = new ArrayList<>();
        List<Map<String,Object>> topPic = cacheService.wzSysFile(EnWzSysFile.Type_Index_Top_Pics.getIndex());
        for(Map<String,Object> map:topPic){
            topPics.add(map);
        }
        //头部图片-广告图片
        List<Map<String,Object>> topAdvPics = cacheService.wzSysFile(EnWzSysFile.Type_Index_Top_Adv_Pics.getIndex());
        //活动中心图片
        List<Map<String,Object>> activityPics = cacheService.wzSysFile(EnWzSysFile.Type_Index_Activity_Pics.getIndex());
        //中部图片
        List<Map<String,Object>> middlePics = cacheService.wzSysFile(EnWzSysFile.Type_Index_Middle_Pics.getIndex());
        //头部图片-红包图片
        List<Map<String,Object>> topRedpacketPic = cacheService.wzSysFile(EnWzSysFile.Type_Index_Top_Repacket_Pic.getIndex());
        //顶部刷新图片
        List<Map<String,Object>> topRefreshPic = cacheService.wzSysFile(EnWzSysFile.Type_Refresh_Pic.getIndex());
        paramMap.clear();
        paramMap.put("topAdvPics",topAdvPics);
        paramMap.put("activityPics",activityPics);
        paramMap.put("middlePics",middlePics);
        paramMap.put("topRedpacketPic",topRedpacketPic.get(0));
        paramMap.put("topRefreshPic",topRefreshPic.get(0));
        //未登录
        if(userCode == null){
            paramMap.put("topPics",topPics);
            paramMap.put("userAdvRecords",userAdvRecords);
            return Res.success(paramMap);
        }else{//登录状态
            userAdvRecords = userAdvRecordMapper.selectMaps(new EntityWrapper<WzUserAdvRecord>().setSqlSelect("adv_id As jumpTarget").eq("user_code",userCode).eq("subtype",EnWzAdv.SUBTYPE_ADV.getIndex()).ge("create_time", DateUtil.yesterday(new Date(),15)));
            List<Map<String,Object>>  userRedpacketRecord = userAdvRecordMapper.selectMaps(new EntityWrapper<WzUserAdvRecord>().setSqlSelect("adv_map_id As jumpTarget").eq("user_code",userCode).eq("subtype",EnWzAdv.SUBTYPE_Redpacket_MapAdv.getIndex()).ge("create_time", DateUtil.yesterday(new Date(),10)));
            for(Map<String,Object> map:userRedpacketRecord){
                userAdvRecords.add(map);
            }
            paramMap.put("userAdvRecords",userAdvRecords);
            //广告
            String sql = "adv_id As jumpTarget,title,subtitle,cover_url As fileUrl,subtype As type,subtype As jumpType,subtype As height";
            List<Map<String,Object>> advs = advMapper.selectMaps(new EntityWrapper<WzAdv>().setSqlSelect(sql).eq("daily_total_number",0).like("screen_city",switchAdCode).eq("status",EnWzAdv.STATUS_RELEASE_no.getIndex()).eq("subtype",EnWzAdv.SUBTYPE_ADV.getIndex()).orderBy("release_time",false));
            for(Map<String,Object> map:advs){
                topPics.add(map);
            }
            //红包
            sql = "adv_map_id As jumpTarget,title,'' As subtitle,cover_url As fileUrl,subtype As type,subtype As jumpType,subtype As height";
            List<Map<String,Object>> redpackets = advMapper.selectMaps(new EntityWrapper<WzAdv>().setSqlSelect(sql).like("screen_city",switchAdCode).eq("status",EnWzAdv.STATUS_RELEASE_no.getIndex()).eq("subtype",EnWzAdv.SUBTYPE_Redpacket_MapAdv.getIndex()).orderBy("release_time",false));
            for(Map<String,Object> map:redpackets){
                topPics.add(map);
            }
            paramMap.put("topPics",topPics);
        }
        return Res.success(paramMap);
    }

    public Res newIndexAdvMapRecommend(ParamMap paramMap) {
        int pageNum = paramMap.getIntMisValid("pageNum");
        int pageSize = paramMap.getIntMisValid("pageSize");
        String switchAdCode = paramMap.getStrValid("switchAdCode");//行政编号
        if(StringUtils.isBlank(switchAdCode)){
            switchAdCode = paramMap.getStrMisValid("adCode");
        }
        //位置判断
        if(switchAdCode.length() != 6){
            return Res.fail(BizExceptionEnum.RES_Ad_Code_Abnormal);
        }
        int advMapCategoryFirst = paramMap.getIntMisValid("advMapCategoryFirst");//一级分类 0:全部
        //sql语句
        String sql = "adv_map_id AS advMapId,avatar_url AS avatarUrl,subtitle,name";
        EntityWrapper<WzAdvMap> entityWrapper=new EntityWrapper<>();
        entityWrapper.setSqlSelect(sql).like("ad_code", switchAdCode).eq("type", EnWzAdvMap.TYPE_Adv.getIndex()).in("status", new Integer[]{EnWzAdvMap.STATUS_Release.getIndex(), EnWzAdvMap.STATUS_RelesseEditors.getIndex(), EnWzAdvMap.STATUS_Edit_Reject.getIndex()});
        if(advMapCategoryFirst!=0){
            entityWrapper.eq("adv_map_category_first",advMapCategoryFirst).orderBy("sort", true).orderBy("daily_amount", false).orderBy("create_time", true);
        }else{
            entityWrapper.eq("is_recommend", EnWzMapActivity.IsRecommend_Yes.getIndex()).orderBy("RAND()");

        }
        List<Map<String, Object>> advMaplist = advMapMapper.selectMapsPage(new Page(pageNum,pageSize),entityWrapper);
        for(Map<String, Object> map:advMaplist){
            int i = 0;
            List<Map<String, Object>> mapActivityList = new ArrayList<>();
            String mapRebateSql = "'' As mapMergeId,map_rebate_id As mapRebateId,benefit,rebate_price As price";
            List<Map<String, Object>> mapRebateList = mapRebateMapper.selectMaps(new EntityWrapper<WzMapRebate>().setSqlSelect(mapRebateSql).eq("adv_map_id",Long.parseLong(map.get("advMapId").toString())).eq("status",EnWzMapRebate.STATUS_RELEASE.getIndex()).orderBy("create_time",true));
            String mapMergeSql = "map_merge_id As mapMergeId,'' As mapRebateId,benefit,merge_price As price";
            List<Map<String, Object>> mapMergeList = mapMergeMapper.selectMaps(new EntityWrapper<WzMapMerge>().setSqlSelect(mapMergeSql).eq("adv_map_id",Long.parseLong(map.get("advMapId").toString())).eq("status",EnWzMapMerge.STATUS_RELEASE.getIndex()).orderBy("create_time",true));
            if(mapRebateList.size() > 0){
                mapActivityList.add(mapRebateList.get(0));
                i++;
            }
            if(mapMergeList.size() > 0){
                mapActivityList.add(mapMergeList.get(0));
                i++;
            }
            if(mapRebateList.size() > 1){
                mapActivityList.add(mapRebateList.get(1));
                i++;
            }
            if(mapMergeList.size() > 1 && i < 4){
                mapActivityList.add(mapMergeList.get(1));
                i++;
            }
            if(mapRebateList.size() > 2 && i < 4){
                mapActivityList.add(mapRebateList.get(2));
                i++;
            }
            if(mapMergeList.size() > 2 && i < 4){
                mapActivityList.add(mapMergeList.get(2));
            }
            map.put("mapActivityList",mapActivityList);
        }
        return Res.success(paramMap.data(advMaplist));
    }
}
